/*
 * @file    : Button.c
 * @author  : Larissa
 * @brief   : xxx module Header file
 */

#include "Button.h"
#include <stdbool.h>
#include <stdint.h>
#include <null.h>
#include "Port.h"
#include "FactoryTest.h"

typedef enum {
	BUTTON_STATE_RELEASE = 0,
	BUTTON_STATE_PRESS,
}BUTTON_STATE;

typedef void (*func)(uint8_t param);

typedef struct {
	GPIO_Port_Type portIdx;
	BUTTON_STATE state;
	uint8_t triggerVoltage; // don't change
	func callBack;
	uint8_t param;
}Button_State;

static Button_State buttons[] = {
		{// button up
				.portIdx = GPIO_Port_C0,
				.state = BUTTON_STATE_RELEASE,
				.triggerVoltage = 1,
				.callBack = FactoryTest_Request,
				.param = SIG_PRE
		},
		{// button down
				.portIdx = GPIO_Port_D9,
				.state = BUTTON_STATE_RELEASE,
				.triggerVoltage = 1,
				.callBack = FactoryTest_Request,
				.param = SIG_NEXT
		},
		{// button start
				.portIdx = GPIO_Port_E16,
				.state = BUTTON_STATE_RELEASE,
				.triggerVoltage = 0,
				.callBack = FactoryTest_Request,
				.param = SIG_START
		},
		{// button stop
				.portIdx = GPIO_Port_E15,
				.state = BUTTON_STATE_RELEASE,
				.triggerVoltage = 0,
				.callBack = FactoryTest_Request,
				.param = SIG_STOP
		}
};

static const uint8_t buttons_len = sizeof(buttons) / sizeof(buttons[0]);

void Button_Init(void)
{
	for(int i = 0; i < buttons_len; i ++)
	{
		Port_GPIOInit(buttons[i].portIdx, GPIO_IN);
	}
}

void Button_10ms(void)
{
	uint8_t portState = 0;

	for(int i = 0; i < buttons_len; i ++)
	{
		portState = Port_GPIRead(buttons[i].portIdx);

		if(portState == buttons[i].triggerVoltage)
		{
			if(buttons[i].state != BUTTON_STATE_PRESS)
			{
				buttons[i].state = BUTTON_STATE_PRESS;
				if(buttons[i].callBack)
				{
					buttons[i].callBack(buttons[i].param);
				}
			}
		}
		else
		{
			if(buttons[i].state != BUTTON_STATE_RELEASE)
			{
				buttons[i].state = BUTTON_STATE_RELEASE;
			}
		}
	}

}

